﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace SnapLib
{
   public class HBitmap :IDisposable
   {
      internal IntPtr m_handle;
      internal DC m_selectedTo = null;
      internal IntPtr m_old = IntPtr.Zero;

      internal HBitmap(DC dc, Size size)
      {
         m_handle = Win32.CreateCompatibleBitmap(dc.Handle, size.Width, size.Height);
         if(m_handle==IntPtr.Zero)
            throw new Exception("Error creating HBitmap");
      }

      public void SelectInto(DC dc)
      {
         ReleaseSelection();
         m_selectedTo = dc;
         m_old = Win32.SelectObject(dc.Handle, m_handle);
      }

      public void ReleaseSelection()
      {
         if (m_selectedTo != null)
         {
            Win32.SelectObject(m_selectedTo.Handle, m_old);
            m_selectedTo = null;
         }
      }

      public Bitmap Bitmap    
      {
         get
         {
            return Image.FromHbitmap(m_handle);
         }
      }

      public void Dispose()
      {
         Win32.DeleteObject(m_handle);
      }
   }
}
